﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Touchless.Demo
{
    class myClient
    {
        ClientInfo client;
        Socket socket;
        public short targetX, targetY;
        int windowWidth, windowHeight;
        DateTime currTime, targetTime;
        Networking parent;

        public myClient(Networking p, int x, int y)
        {
            parent = p; windowWidth = x; windowHeight = y;

            string ipAddress = string.Empty;
            int port = 0;
            try
            {
                ipAddress = parent.IPAddress1.Text + "." + parent.IPAddress2.Text + "." + parent.IPAddress3.Text + "." + parent.IPAddress4.Text;
                port = Int32.Parse(parent.portTextBox.Text);
            }
            catch (Exception e)
            {
                parent.MessageBoxShow(string.Format("Invalid IP address.\nError: {0}", e.Message));
                parent.toggleControls(true);
                return;
            }

            try
            {
                socket = Sockets.CreateTCPSocket(ipAddress, port);
                client = new ClientInfo(socket, false);
                client.MessageType = MessageType.Length;
                client.OnReadMessage += new ConnectionReadMessage(extractData);
                client.BeginReceive();
            }
            catch (Exception e)
            {
                parent.MessageBoxShow(string.Format("Something went wrong connecting to the server!\nError: {0}", e.Message));
                parent.toggleControls(true);
                return;
            }
        }

        private void extractData(ClientInfo ci, uint code, byte[] bytes, int len)
        {
            byte[] temp = new byte[2];
            temp[0] = bytes[0]; temp[1] = bytes[1];
            targetX = BitConverter.ToInt16(temp, 0);
            temp[0] = bytes[2]; temp[1] = bytes[3];
            targetY = BitConverter.ToInt16(temp, 0);
            byte[] hours = new byte[2];
            hours[0] = bytes[4]; hours[1] = bytes[5];
            byte[] mins = new byte[2];
            mins[0] = bytes[6]; mins[1] = bytes[7];
            byte[] secs = new byte[2];
            secs[0] = bytes[8]; secs[1] = bytes[9];
            byte[] ms = new byte[2];
            ms[0] = bytes[10]; ms[1] = bytes[11];
            currTime = DateTime.Now;
            targetTime = new DateTime(currTime.Year, 
                                      currTime.Month, 
                                      currTime.Day, 
                                      BitConverter.ToInt32(hours, 0), 
                                      BitConverter.ToInt32(mins, 0), 
                                      BitConverter.ToInt32(secs, 0), 
                                      BitConverter.ToInt32(ms, 0));
        }
    }
}
